package rent.hj.launcher.statusbar;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.RemoteException;
import android.provider.Settings;

import java.io.File;
import java.util.Map;
import java.util.UUID;

/**
 * Created by admin on 2017/11/22.
 */

public class StatusBarPolicy {
    private static final String TAG = "StatusBarPolicy";
    private StatusBar mStatusBar;
    private Context mContext = null;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED) ||
                    action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
                updateBluetooth();
            } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
                updateHeadset(intent);
            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)
                    || action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)
                    || action.equals(WifiManager.RSSI_CHANGED_ACTION)) {
                updateWiFi();
            } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)
                    || action.equals(Intent.ACTION_BATTERY_LOW)) {
                updateBattery(intent);
            } else if (action.equals(Intent.ACTION_TIMEZONE_CHANGED)
                    || action.equals(Intent.ACTION_TIME_CHANGED)
                    || action.equals(Intent.ACTION_TIME_TICK)) {
                updateTime();
            } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
                updateAirplane();
            } else if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)
                    || action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
                updateUSB();
            } else if (action.equals(Intent.ACTION_DEVICE_STORAGE_LOW)
                    || action.equals(Intent.ACTION_DEVICE_STORAGE_OK)
                    || action.equals(Intent.ACTION_DEVICE_STORAGE_FULL)) {
                updateStorage(action);
            }
        }
    };

    private UsbManager mUsbManager = null;

    private int GLASSES_VENDOR_ID = 0x0416, GLASSES_PRODUCT_ID = 0x50A1;
    //1 为存在 ，0 为不存在
    private int GLASSES_DEVICE_FLAG = 0;
    private static final String SDCARD_PATH = "/mnt/external_sd";

    public StatusBarPolicy(Context context) {
        mContext = context;

        mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

        IntentFilter filter = new IntentFilter();

        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction(Intent.ACTION_HEADSET_PLUG);

        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.RSSI_CHANGED_ACTION);

        filter.addAction(android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        filter.addAction(Intent.ACTION_BATTERY_LOW);

        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIME_TICK);

        filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);

        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);

        filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
        filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
        filter.addAction(Intent.ACTION_DEVICE_STORAGE_FULL);

        context.registerReceiver(mIntentReceiver, filter);

    }

    public void setCallBack(StatusBar statusBar) {
        mStatusBar = statusBar;

        updateAll();
    }

    private final void updateBluetooth() {
        if (mStatusBar != null) {
            mStatusBar.onUpdateBluetooth();
        }
    }

    private boolean hasMicrophone = false;
    private boolean isHeadSetActive = false;

    private final void updateHeadset(Intent intent) {

        if (intent != null) {
            this.hasMicrophone = intent.getIntExtra("microphone", 0) == 1 ? true : false;
            this.isHeadSetActive = intent.getIntExtra("state", 0) == 1 ? true : false;
        }

        if (mStatusBar != null) {
            mStatusBar.onUpdateHeadset(hasMicrophone, isHeadSetActive);
        }
    }

    private void updateTime() {
        if (mStatusBar != null) {
            mStatusBar.onUpdateTime();
        }
    }

    private void updateWiFi() {
        if (mStatusBar != null) {
            mStatusBar.onUpdateWiFi();
        }
    }

    private void updateAirplane() {
        if (mStatusBar != null) {
            mStatusBar.onUpdateAirplane(isAirplaneActive());
        }
    }

    private int batteryValuePercent = 0;
    private boolean isCharging = false;

    private void updateBattery(Intent intent) {

        if (intent != null) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
            int percent = (level * 100) / scale;

            batteryValuePercent = percent;

            int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);//充电设备
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
                    BatteryManager.BATTERY_STATUS_UNKNOWN);

            if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
                isCharging = true;
            } else {
                isCharging = false;
            }
        }

        if (mStatusBar != null) {
                mStatusBar.onUpdateBattery(isCharging, batteryValuePercent);
        }
    }

    private void updateStorage(String state) {

        if (mStatusBar != null) {
                mStatusBar.onUpdateStorage(state);
        }
    }

    private void updateUSB() {
        if (mStatusBar != null) {
                mStatusBar.onUpdateUSB(isUsbDevicesExist());
        }
    }

    public boolean isUsbDevicesExist() {

        int size = mUsbManager.getDeviceList().size();

        if (checkGlassesUsbDeviceIsExist()) {
            if (size > 1) return true;
        } else {
            if (size > 0) return true;
        }
        return false;
    }

    //检查眼镜设备是否存在，因为眼镜内置usb设备
    private boolean checkGlassesUsbDeviceIsExist() {
        for (Map.Entry<String, UsbDevice> entry : mUsbManager.getDeviceList().entrySet()) {

            int vendorId = entry.getValue().getVendorId();
            int productId = entry.getValue().getProductId();

            if (vendorId == GLASSES_VENDOR_ID && productId == GLASSES_PRODUCT_ID) {
                GLASSES_DEVICE_FLAG = 1;
                return true;
            }
        }
        GLASSES_DEVICE_FLAG = 0;
        return false;
    }

    public void updateAll() {
        updateBluetooth();
        updateTime();
        updateBattery(null);
        updateAirplane();
        updateHeadset(null);
        updateUSB();
        updateWiFi();
        updateBattery(null);
    }

    public boolean isHasMicrophone() {
        return hasMicrophone;
    }

    public boolean isHeadSetActive() {
        return isHeadSetActive;
    }

    public int getBatteryValuePercent() {
        return batteryValuePercent;
    }

    public boolean isCharging() {
        return isCharging;
    }

    public boolean isSDCardActive() {
        return new File(SDCARD_PATH).listFiles() != null ? true : false;
    }

    public boolean isAirplaneActive() {
        return Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
    }

    public void onDestory() {
        mContext.unregisterReceiver(mIntentReceiver);
    }

}
